package com.vdong.trade.trading.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vdong.trade.order.facade.OrderFacade;
import com.vdong.trade.trading.common.enums.TradeDealTypeEnum;
import com.vdong.trade.trading.common.enums.UserTypeEnum;
import com.vdong.trade.trading.common.exception.ProcessException;
import com.vdong.trade.trading.common.foundation.FoundationCRUDOperation;
import com.vdong.trade.trading.entity.dto.MerchantDetailDTO;
import com.vdong.trade.trading.entity.dto.MerchantRecordResultDTO;
import com.vdong.trade.trading.entity.dto.MerchantTotalListResultDTO;
import com.vdong.trade.trading.entity.dto.param.CountOrderParamDTO;
import com.vdong.trade.trading.entity.dto.param.SettlementParamDTO;
import com.vdong.trade.trading.entity.dto.result.*;
import com.vdong.trade.trading.entity.mo.*;
import com.vdong.trade.trading.entity.po.FinanceParamDTO;
import com.vdong.trade.trading.entity.po.SettlementTotalParamDTO;
import com.vdong.trade.trading.respository.TradingMOMapper;
import com.vdong.trade.trading.service.SettlementService;
import lombok.extern.slf4j.Slf4j;
import org.lamb.framework.common.remote.FacadeResult;
import org.lamb.framework.common.util.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.vdong.trade.trading.common.enums.ProcessExceptionEnum.EB00000002;
import static com.vdong.trade.trading.common.enums.ProcessExceptionEnum.EB00000005;


/**
 * @author zhoulongbiao
 * @Date 2018/12/6 15:07
 */

@Service
@Slf4j
public class SettlementServiceImpl extends FoundationCRUDOperation implements SettlementService {

    @Resource
    private TradingMOMapper tradingMOMapper;

    @Reference
    private OrderFacade orderFacade;


    @Override
    public PageInfo<MerchantTotalListResultDTO> settlementTotalList(SettlementTotalParamDTO param) {
        log.info("settlementTotalList,入参为:[{}]", JSON.toJSONString(param));
        return PageHelper.startPage(param.getPageNum(), param.getPageSize())
                .doSelectPageInfo(() -> {
                    List<MerchantTotalListResultMO> molist = tradingMOMapper.settlementMerchantTotalList(param);
                    for (MerchantTotalListResultMO mo : molist) {
                        mo.setTotalDealMoney(BigDecimal.ZERO);
                        String result = orderFacade.sumOrderMoney
                                (JSON.toJSONString(SettlementParamDTO.builder().userType(param.getUserType())
                                        .userId(mo.getUserId()).build()));
                        MoneyAndCountMO data = FacadeResultUtils.stringToFacadeBean(result, MoneyAndCountMO.class).getData();
                        if (!StringUtil.hasBlank(data.getSumOrderMoney())) {
                            mo.setTotalDealMoney(new BigDecimal(data.getSumOrderMoney()));
                        }
                    }
                    CopyUtil.copyList(molist, MerchantTotalListResultDTO.class);
                });
    }

    @Override
    public PageInfo<MerchantRecordResultDTO> settlementRecord(SettlementTotalParamDTO param) {
        log.info("settlementRecord,入参为:[{}]", JSON.toJSONString(param));
        param.setDealType(TradeDealTypeEnum.ORDER_PUSHER_SUCCESS.getType());
        if ("-1".equals(param.getSettleStatus())) {
            param.setSettleStatus(null);
        }
        PageInfo<MerchantRecordResultDTO> resultPageInfo = PageHelper.startPage(param.getPageNum(), param.getPageSize())
                .doSelectPageInfo(() -> {
                    CopyUtil.copyList
                            (Optional.ofNullable(tradingMOMapper.settlementMerchantRecord(param))
                                    .orElseThrow(() -> new ProcessException(EB00000005)), MerchantRecordResultDTO.class);
                });
        return resultPageInfo;
    }

    @Override
    public PageInfo<MerchantDetailDTO> settlementDetail(SettlementTotalParamDTO param) {
        log.info("settlementDetail,入参为:[{}]", JSON.toJSONString(param));
        param.setDate(DateUtil.stampToDate(param.getDate()));
        PageInfo<MerchantDetailDTO> resultPageInfo = PageHelper.startPage(param.getPageNum(), param.getPageSize())
                .doSelectPageInfo(() -> {
                    CopyUtil.copyList
                            (Optional.ofNullable(tradingMOMapper.settlementMerchantDetail(param))
                                    .orElseThrow(() -> new ProcessException(EB00000005)), MerchantDetailDTO.class);
                });
        return resultPageInfo;
    }

    @Override
    public MerchantSettlementAllResultDTO settlementAll(SettlementTotalParamDTO param) {
        log.info("settlementAll,入参为:[{}]", JSON.toJSONString(param));
        MerchantSettlementAllMO merchantSettlementAllMO = tradingMOMapper.settlementAll(param);

        MerchantSettlementAllResultDTO resultDTO = new MerchantSettlementAllResultDTO();
        if (StringUtil.hasBlank(merchantSettlementAllMO)) {
            resultDTO.setTotalSettlement("0");
            resultDTO.setStaySettlement("0");
        } else {
            if (StringUtil.hasBlank(merchantSettlementAllMO.getTotalSettlement())) {
                resultDTO.setTotalSettlement("0");
            } else {
                resultDTO.setTotalSettlement(merchantSettlementAllMO.getTotalSettlement());
            }

            if (StringUtil.hasBlank(merchantSettlementAllMO.getStaySettlement())) {
                resultDTO.setStaySettlement("0");
            } else {
                resultDTO.setStaySettlement(merchantSettlementAllMO.getStaySettlement());
            }
        }
        return resultDTO;
    }

    @Override
    public SettlementAllEarningsResultDTO settlementAllEarnings(SettlementTotalParamDTO param) throws Exception {
        log.info("settlementAllEarnings,入参为:[{}]", JSON.toJSONString(param));
        SettlementAllEarningsMO earningsMO = tradingMOMapper.settlementAllEarnings(param);
        SettlementAllEarningsResultDTO resultDTO = new SettlementAllEarningsResultDTO();

        //查询推客所有的订单交易额
        String s = JSON.toJSONString(CountOrderParamDTO.builder().userId(param.getUserId())
                .userType(UserTypeEnum.PUSHER.getValue().toString()).build());
        String result = orderFacade.sumOrderMoney(s);
        log.info("获取到的信息为:[{}]", JSON.toJSONString(result));
        if (StringUtil.hasBlank(result)) throw new ProcessException(EB00000005);
        FacadeResult<TodayAndAllSellMO> result1 = FacadeResultUtils.stringToFacadeBean(result, TodayAndAllSellMO.class);
        TodayAndAllSellMO todayAndAllSellMO = null;
        if (result1.isSuccess()) {
            todayAndAllSellMO = result1.getData();
        }

        if (StringUtil.hasBlank(todayAndAllSellMO)) {
            resultDTO.setTotalDealMoney(BigDecimal.ZERO);
        }

        if (StringUtil.hasBlank(earningsMO)) {
            resultDTO.setAccumulatedSettlement(BigDecimal.ZERO);
            resultDTO.setTotalEarnMoney(BigDecimal.ZERO);
            resultDTO.setTotalStaySettlement(BigDecimal.ZERO);
            return resultDTO;
        }

        if (StringUtil.hasBlank(earningsMO.getAccumulatedSettlement())) {
            resultDTO.setAccumulatedSettlement(BigDecimal.ZERO);
        } else {
            resultDTO.setAccumulatedSettlement(earningsMO.getAccumulatedSettlement());
        }

        if (!StringUtil.hasBlank(todayAndAllSellMO)) {
            assert todayAndAllSellMO != null;
            if (StringUtil.hasBlank(todayAndAllSellMO.getSumOrderMoney())) {
                resultDTO.setTotalDealMoney(BigDecimal.ZERO);
            } else {
                resultDTO.setTotalDealMoney(new BigDecimal(todayAndAllSellMO.getSumOrderMoney()));
            }
        }

        if (StringUtil.hasBlank(earningsMO.getTotalEarnMoney())) {
            resultDTO.setTotalEarnMoney(BigDecimal.ZERO);
        } else {
            resultDTO.setTotalEarnMoney(earningsMO.getTotalEarnMoney());
        }

        if (StringUtil.hasBlank(earningsMO.getTotalStaySettlement())) {
            resultDTO.setTotalStaySettlement(BigDecimal.ZERO);
        } else {
            resultDTO.setTotalStaySettlement(earningsMO.getTotalStaySettlement());
        }

        return resultDTO;
    }

    @Override
    public SettlementDetailsEarningsResultDTO settlementDetailEarnings(SettlementTotalParamDTO param) throws Exception {
        log.info("settlementDetailEarnings,入参为:[{}]", JSON.toJSONString(param));
        param.setDate(DateUtil.stampToDate(param.getDate()));
        log.info("param,入参为:[{}]", JSON.toJSONString(param));
        MerchantSettlementAllMO merchantSettlementAllResultDTO = tradingMOMapper.settlementDetailEarnings(param);
        log.info("merchantSettlementAllResultDTO:[{}]", JSON.toJSONString(merchantSettlementAllResultDTO));
        if (StringUtil.hasBlank(merchantSettlementAllResultDTO)) {
            merchantSettlementAllResultDTO.setSettlementMoney("0");
        }
        String s = JSON.toJSONString(param);
        log.info("hu=====,[{}]", JSON.toJSONString(s));
        String result = orderFacade.orderTransaction(s);
        if (StringUtil.hasBlank(result)) throw new ProcessException(EB00000005);
        OrderTransactionResultDTO dto = FacadeResultUtils.stringToFacadeBean
                (result, OrderTransactionResultDTO.class).getData();
        String orderMoney = "";
        if (StringUtil.hasBlank(dto.getOrderMoney())) {
            orderMoney = "0";
        } else {
            orderMoney = String.valueOf(dto.getOrderMoney());
        }
        return SettlementDetailsEarningsResultDTO.builder()
                .settlementMoney(merchantSettlementAllResultDTO.getSettlementMoney())
                .orderMoney(orderMoney)
                .countOrder(String.valueOf(dto.getCountOrder())).build();
    }

    @Override
    public PusherSettlementAndCountResultDTO pusherSettlementAndCount(SettlementTotalParamDTO param) {
        log.info("pusherSettlementAndCount,入参为:[{}]", JSON.toJSONString(param));
        PusherSettlementAndCountMO mo = tradingMOMapper.pusherSettlementAndCount(param);
        String resultOrder = orderFacade.pusherTodayAndAllSell(JSON.toJSONString
                (FinanceParamDTO.builder().pusherKey(param.getUserId()).build()));
        if (StringUtil.hasBlank(resultOrder)) throw new ProcessException(EB00000005);
        TodayAndAllSellResultDTO dto = FacadeResultUtils.stringToFacadeBean(resultOrder,
                TodayAndAllSellResultDTO.class).getData();
        return PusherSettlementAndCountResultDTO.builder()
                .totalSettlement(mo.getTotalSettlement())
                .totalEarnings(mo.getTotalEarnings())
                .totalCount("1").build();
    }

}
